package com.xingxuecn.limit.common.utils;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

/**
 * @author Kris at 2018/9/4 17:34
 */
public class DbUtils {
    private DbUtils(){}

    private static DataSource dataSource;

    /**
     * 获取数据源
     * @return
     */
    public static DataSource getDataSource() {
        if(dataSource == null){
            initDataSource();
        }
        return dataSource;
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }


    /**
     * 初始化数据源
     */
    private static void initDataSource(){
        Properties pro = new Properties();
        try {
            pro.load(DbUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        dataSource = new DruidDataSource();
        ((DruidDataSource) dataSource).configFromPropety(pro);
    }
}
